<template>
	<view class="changeInfo">
		<uni-nav-bar dark :fixed="true" :border="false" background-color="#FFFFFF" status-bar title="个人信息"
			left-icon="left" @clickLeft="toBack" color="#000" />
		<view>
			<u-cell-group>
				<u-cell clickable title="头像" @click="chooseImg">
					<view slot="value" class="userImsage">
						<image :src="READ_IMG_URL+userInfo.image" class="circle-image"></image>
					</view>
				</u-cell>
				<u-cell title="姓名" :value="userInfo.nickName"></u-cell>
				<u-cell clickable title="性别" :value="array[0][userInfo.sex]" @click="sexShow = true">
				</u-cell>
				<u-cell title="手机号" :value="userInfo.phone"></u-cell>
				<u-cell title="职位" :value="role.nameZh"></u-cell>
				<u-cell clickable title="绑定微信(自动登录)" :value="isBindText()"
					@click="bindWx">
				</u-cell>
				<u-cell clickable title="修改密码" @click="show = true"></u-cell>
			</u-cell-group>
		</view>
		<!-- 性别 -->
		<u-picker :show="sexShow" :columns="array" @confirm="confirm" @close="sexClose" 
			@cancel="sexClose" :closeOnClickOverlay="true">
		</u-picker>
		</picker>
		<!-- 修改密码 -->
		<u-popup :show="show" @close="close" mode="bottom" >
			<view style="width: 90%;height: 450rpx; margin: auto;">
<!-- 				<view style="height: 100rpx;line-height: 100rpx;text-align: center;
					font-size: 45rpx;font-weight: bold;">
					<text>修改密码</text>
				</view> -->
				<u--form ref="pwdForm" :model="pwd" :labelWidth="80">
					<u-form-item label="新的密码" prop="password">
						<u-input v-model="pwd.password" type="password" border="bottom" />
					</u-form-item>
					<u-form-item label="确认密码" prop="verifyPwd">
						<u-input v-model="pwd.verifyPwd" type="password" border="bottom" />
					</u-form-item>
				</u--form>
				<view style="margin: auto;margin-top: 20px;width: 80%;">
					<u-button shape="circle" type="primary" @click="changePwd">
						确定
					</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import api from '../../../request/api'
	import config from '../../../request/config'
	import userApi from '../../../request/userApi'
	export default {
		data() {
			return {
				isBind: 0,
				show: false,
				READ_IMG_URL: config.READ_IMG_URL,
				userInfo: {},
				sexShow: false,
				roleList: [],
				role: {},
				array: [
					['男', '女']
				],
				pwd: {
					password: '',
					verifyPwd: '',
				},
				verifyRules: {
					'password': {
						type: 'string',
						required: true,
						message: '请输入密码！',
						trigger: ['blur', 'change']
					},
					'verifyPwd': [{
						type: 'string',
						required: true,
						message: '请确认密码！',
						trigger: ['blur', 'change']
					}, {
						// 自定义验证函数
						validator: (rule, value, callback) => {
							if (value === this.pwd.password){
								return true;
							}
							return false;
						},
						message: '两次输入的密码不匹配',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur'],
					}]
				}
			}
		},
		onLoad() {
			this.userInfo = uni.getStorageSync("loginUser")
			this.userInfo.roleId = parseInt(this.userInfo.roleId)
			//console.log("this.userInfo=>", this.userInfo)
			this.getRoleList();
			this.getUser();
		},
		onReady() {
			this.$refs.pwdForm.setRules(this.verifyRules)
		},
		methods: {
			// 返回上个页面
			toBack() {
				uni.navigateBack({
					delta: 1, // 返回的页面数，1表示返回上一页
					animationType: 'pop-out', // 页面关闭的动画效果
					animationDuration: 300, // 页面关闭的动画时间
				});
			},
			// 获取个人信息
			getUser(){
				const data = {
					id: this.userInfo.id
				}
				userApi.getUser(data).then(res =>{
					if (res.code === 200){
						this.userInfo = res.data
						this.userInfo.roleId = parseInt(this.userInfo.roleId)
						uni.setStorageSync("loginUser", this.userInfo)
					}
				})
			},
			// 获取角色列表
			getRoleList() {
				api.getRoleList().then(res => {
					if (res.code === 200) {
						this.roleList = res.data
						this.role = this.roleList.find(item => item.id === this.userInfo.roleId)
						//console.log("role=>", this.role)
					}
				})
			},
			// 选择性别
			confirm(e) {
				//console.log("e=>",e.indexs[0])
				this.userInfo.sex = e.indexs[0];
				this.updateUser();
				this.sexClose();
			},
			sexClose() {
				this.sexShow = false;
			},
			// 修改用户
			updateUser() {
				uni.showLoading({
					title: "请求中...",
					mask: true
				})
				userApi.updateUser(this.userInfo).then(res => {
					if (res.code === 200) {
						this.userInfo = res.data
						uni.setStorageSync("loginUser", this.userInfo)
						uni.hideLoading();
						uni.showToast({
							icon: "success",
							title: '修改成功'
						});
					}
				})
			},
			// 选择头像
			chooseImg() {
				uni.showToast
				uni.chooseMedia({
					count: 1,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					camera: 'back',
					success: (res) => {
						//console.log("tempFiles=>", res.tempFiles)
						this.uploadImg(res.tempFiles[0].tempFilePath)
					}
				})
			},
			// 上传头像
			uploadImg(tempFilePath) {
				console.log("tempFilePath=>", tempFilePath)
				uni.showLoading({
					title: "上传中...",
					mask: true
				})
				const uploadUrl = config.IMG_URL
				uni.uploadFile({
					url: uploadUrl,
					filePath: tempFilePath,
					name: 'file',
					header: {
						"OaAuth": uni.getStorageSync("OaAuth") || ''
					},
					success: (res) => {
						console.log("res=>", res)
						let data = JSON.parse(res.data);
						if (data.code === 200) {
							this.userInfo.image = data.data
							uni.hideLoading();
							this.updateUser()
						} else {
							uni.hideLoading();
							uni.showToast({
								icon: "error",
								title: '上传失败'
							});
						}
					}
				});
			},
			// 修改密码
			changePwd() {
				this.$refs.pwdForm.validate().then(res => {
					uni.showLoading({
						title: "请求中...",
						mask: true
					})
					const data = {
						id: this.userInfo.id,
						password: this.pwd.password
					}
					userApi.changePassword(data).then(res =>{
						if (res.code === 200){
							this.close();
							uni.showToast({
								icon: "success",
								title: '修改成功'
							});
						}
						uni.hideLoading();
					}).finally(() =>{
						uni.hideLoading();
					})
				}).catch(errors => {
					console.log('校验失败')
				})
			},
			// 关闭修改密码弹窗
			close() {
				this.pwd.password = ''
				this.pwd.verifyPwd = ''
				this.show = false
			},
			// 
			isBindText(){
				if (this.userInfo.openId != null){
					return "已绑定"
				}
				return "未绑定"
			},
			// 绑定微信
			bindWx(){
				let _this = this
				if (this.userInfo.openId != null){
					uni.showModal({
						title: '提示',
						content: '确定要解除绑定吗？',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								_this.isBind = 1;
								_this.submitData();
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}else {
					_this.submitData();
				}
			},
			submitData(){
				let _this = this
				uni.showLoading({
					title: "请求中...",
					mask: true
				})
				uni.login({
					success: (response) =>{
						if (response.errMsg === 'login:ok') {
							const data = {
								code: response.code,
								isBind: _this.isBind
							}
							userApi.bindWx(data).then(res =>{
								_this.getUser()
								_this.$tip.tip(res.message)
							}).finally(() =>{
								uni.hideLoading();
							})
						}else {
							uni.hideLoading();
							_this.$tip.tip('系统异常，请联系管理员')
						}
					},
				})
			}
		}
	}
</script>

<style>
	.userImsage {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		/* 将容器变为圆形 */
		overflow: hidden;
	}

	.circle-image {
		max-width: 100%;
		max-height: 100%;
		object-fit: cover;
	}
</style>